import os
import sys
import pygame
from PyQt6.QtWidgets import  QTextEdit, QFrame, QHBoxLayout, QLabel, QPushButton
from PyQt6.QtGui import QMouseEvent, QTextOption, QPainter, QColor, QIcon, QDesktopServices
from PyQt6.QtCore import Qt, QSize, QUrl


# 获取当前进程ID
current_pid = os.getpid()
print(f"进程ID：{current_pid}")

# 定义缓存文件路径
CACHE_FILE = './cache.json'

swi_thr = False

swi_dd = False

swi_vars = {}

thr_sta = []

key_mode = "开关模式"

key_delay = 5

version = "v1.1.3"

o_env = 0  # 程序运行环境

if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
    # PyInstaller 打包环境
    o_env = 1
    print("PyInstaller 打包环境")
else:
    # 开发环境 / Nuitka打包环境
    o_env = 0
    print("开发环境 / Nuitka打包环境")

def resource_path(relative_path):
    """获取打包后的资源文件路径"""
    if o_env == 1:
        # PyInstaller 打包环境
        base_path = sys._MEIPASS
    else:
        # 如果是在 开发环境 / Nuitka打包环境 中运行
        base_path = os.path.dirname(os.path.abspath(__file__))
        # base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

def of_icon_path():
    if swi_thr == True:
        icon = resource_path("停止.svg")
    else:
        icon = resource_path("播放.svg")
    return icon

def play_sound(sound_file):
    """播放声音文件"""
    sound_path = resource_path(sound_file)
    try:
        sound = pygame.mixer.Sound(sound_path)
        sound.play().set_endevent(pygame.USEREVENT)  # 设置播放完成事件
    finally:
        del sound  # 强制释放资源

# 自定义标题栏类
class CustomTitleBar(QFrame):
    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent
        self.setFixedHeight(30)  # 设置标题栏高度
        # self.setStyleSheet(
        #     "background-color: rgba(255,255,255,1);"
        #     )
        
        layout = QHBoxLayout()  # 创建水平布局
        layout.setContentsMargins(8, 2, 8, 2)  # 设置布局边距
        # layout.setSpacing(4)  # 设置布局间距为 3
        
        # 滴斗logo图标按钮
        self.didou_button = QPushButton(self)
        self.didou_button.setIcon(QIcon(resource_path("didou.svg")))  # 设置图标，使用图标文件路径
        self.didou_button.setIconSize(QSize(18, 18))
        self.didou_button.clicked.connect(self.open_url)  # 连接点击事件到处理方法
        self.didou_button.setStyleSheet(
            """
            QPushButton {
                background-color: rgba(100, 100, 100, 0); /* 半透明背景 */
                border: 0px; /* 焦点状态的边框宽度和颜色 */
                width: 18px;
            }
            QPushButton:pressed { 
                padding-left: 2px; /* 增加内边距 */
                padding-top: 1px; /* 增加内边距 */
            }
            """
        )
        layout.addWidget(self.didou_button)  # 将图标添加到布局中

        self.title_label = QLabel(f"滴斗按键 {version}", self)  # 标题标签
        self.title_label.setStyleSheet("background-color: rgba(0,0,0,0); font-family: 'Microsoft YaHei'; font-size: 13px;")  # 设置标签样式
        layout.addWidget(self.title_label)  # 将标签添加到布局中
        
        # 添加一个伸缩空间以将按钮推到右边
        layout.addStretch()
        
        # 最小化按钮
        self.minimize_button = QPushButton("-", self)  # 最小化按钮
        self.minimize_button.setFixedSize(14, 14)  # 设置按钮大小
        # self.minimize_button.setStyleSheet("background-color: #34a853; padding-bottom: 2px; color: white; font-family: 'Microsoft YaHei'; border-radius: 10px;")  # 设置按钮样式
        self.minimize_button.setStyleSheet(
            """
            QPushButton {
                background-color: rgba(52, 168, 83, 1);
                font-size: 16px;
                padding-bottom: 3px;
                color: white;
                font-family: 'Microsoft YaHei'; 
                font-weight: bold;
                border-radius: 7px;
            }
            QPushButton:hover { 
                background-color: rgba(41, 153, 71, 1);
            }
            QPushButton:pressed { 
                background-color: rgba(32, 140, 61, 1);
                padding-left: 1px; /* 增加内边距 */
                padding-top: 1px; /* 增加内边距 */
            }
            """
        )
        self.minimize_button.clicked.connect(self.parent.showMinimized)  # 连接最小化按钮的点击事件到父窗口的最小化方法
        layout.addWidget(self.minimize_button)  # 将按钮添加到布局中
        
        # 关闭按钮
        self.close_button = QPushButton("·", self)  # 关闭按钮
        self.close_button.setFixedSize(14, 14)  # 设置按钮大小
        # self.close_button.setStyleSheet("background-color: #ea4335; color: white; border-radius: 10px;")  # 设置按钮样式
        self.close_button.setStyleSheet(
            """
            QPushButton {
                background-color: rgba(234,67,53,1); 
                font-size: 25px;
                padding-bottom: 3px;
                color: white; 
                border-radius: 7px;
            }
            QPushButton:hover { 
                background-color: rgba(217, 62, 49, 1);
            }
            QPushButton:pressed { 
                background-color: rgba(211,60,47,1); 
                padding-left: 1px; /* 增加内边距 */
                padding-top: 1px; /* 增加内边距 */
            }
            """
        )
        self.close_button.clicked.connect(self.parent.close)  # 连接关闭按钮的点击事件到父窗口的关闭方法
        layout.addWidget(self.close_button)  # 将按钮添加到布局中
        
        self.setLayout(layout)  # 设置标题栏的布局
        
        self.drag_position = None  # 初始化拖动位置

    def open_url(self):
        # 指定要打开的网址
        url = QUrl("https://www.jx3box.com/tool/94312")
        
        # 使用QDesktopServices打开网址
        if not QDesktopServices.openUrl(url):
            print("无法打开网址")

    def mousePressEvent(self, event: QMouseEvent):
        if event.button() == Qt.MouseButton.LeftButton:
            self.drag_position = event.globalPosition().toPoint() - self.parent.frameGeometry().topLeft()  # 记录拖动起始位置
            event.accept()  # 接受事件
    
    def mouseMoveEvent(self, event: QMouseEvent):
        if event.buttons() == Qt.MouseButton.LeftButton and self.drag_position is not None:
            self.parent.move(event.globalPosition().toPoint() - self.drag_position)  # 移动窗口
            event.accept()  # 接受事件

class CenteredTextEdit(QTextEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet(
            """
            QTextEdit {
                font-family: 'Microsoft YaHei';
                background-color: rgba(100, 100, 100, 30); /* 半透明背景 */
                font-size: 13px;
                border-radius: 5px;
                padding: 10px; /* 增加内边距 */
            }
            QTextEdit:focus { 
                border: 3px solid #fbbc05; /* 焦点状态的边框宽度和颜色 */
                background-color: rgba(100, 100, 100, 10); /* 可选: 焦点状态背景稍微加深 */
            }
            """
        )
        self.setWordWrapMode(QTextOption.WrapMode.WrapAtWordBoundaryOrAnywhere)  # 自动换行
        self.setAlignment(Qt.AlignmentFlag.AlignCenter)  # 设置文本居中对齐
        self.setAttribute(Qt.WidgetAttribute.WA_InputMethodEnabled, False)        # 禁用输入法
        self.setInputMethodHints(Qt.InputMethodHint.ImhHiddenText)                # 隐藏输入法提示
        self._placeholder_text = ""
        self._placeholder_color = QColor(128, 128, 128, 128)  # 默认占位符颜色

    def setAlignment(self, alignment):
        doc = self.document()
        text_option = doc.defaultTextOption()
        text_option.setAlignment(alignment)
        doc.setDefaultTextOption(text_option)
        self.update()  # 更新文本编辑框

    def setPlaceholderText(self, placeholderText):
        """设置占位符文本"""
        self._placeholder_text = placeholderText
        self.viewport().update()

    def paintEvent(self, event):
        """重绘事件，添加占位符居中逻辑"""
        super().paintEvent(event)
        if not self.toPlainText():  # 仅当文本框为空时显示占位符
            painter = QPainter(self.viewport())
            painter.setPen(self._placeholder_color)
            painter.drawText(
                self.viewport().rect(),
                Qt.AlignmentFlag.AlignCenter,
                self._placeholder_text
            )